import 'dart:convert';
import 'dart:developer' as dev;
import 'dart:math';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_tts/flutter_tts.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:quick_translate/LanguageList.dart';
import 'package:share/share.dart';

// import 'package:shared_preferences/shared_preferences.dart';
import 'package:translator/translator.dart';

import 'LanguagePage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  var localeData;

  @override
  Widget build(BuildContext context) {
    SystemUiOverlayStyle uiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }

// void saveLanguage(Locale deviceLocale) async {
//   SharedPreferences sp = await SharedPreferences.getInstance();
//   sp.setString(
//       'lan',
//       "${deviceLocale.languageCode}-${deviceLocale.countryCode}"
//           .toLowerCase());
// }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String source = "Automatic";
  String target = "English";
  String result;
  // FlutterTts flutterTts = FlutterTts();
  GoogleTranslator translator = GoogleTranslator();
  TextEditingController controller1 = TextEditingController();
  FocusNode focusNode1 = FocusNode();
  List<dynamic> histories = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  trans() async {
    if (controller1.text == null ||
        controller1.text.isEmpty ||
        controller1.text == "") {
      setState(() {
        result = null;
      });
      return;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    Dio dio = Dio();
    // String from = LanguageList.getCode(source);
    String to = LanguageList.getCode(target);
    String q = controller1.text.trim();
    String google_url =
        "http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=$to&q=$q";
    Response response = await dio.get(google_url);
    result = response.data['sentences'][0]['trans'];
    var data = {"source": q, "target": result};
    histories.add(data);
    setState(() {});
  }

  copyWords() {
    Clipboard.setData(ClipboardData(text: result));
    Fluttertoast.showToast(msg: "Copy Success!");
  }

  shareWords() async {
    Share.share(result);
  }

  playWords() async {
    // flutterTts.speak(result);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Color(0xffefefef),
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          brightness: Brightness.light,
          title: Text(
            "Quick Translate",
            style: TextStyle(fontWeight: FontWeight.w500, color: Colors.black),
          ),
        ),
        body: SingleChildScrollView(
            physics: BouncingScrollPhysics(),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        // width: double.infinity,
                        margin: EdgeInsets.symmetric(horizontal: 16),
                        child: InkWell(
                          // onTap: () {
                          //   Navigator.push(context, MaterialPageRoute(builder: (_)=>LanguagePage(source,0))).then((value) {
                          //     if (value != null) {
                          //       source = value;
                          //       setState(() {});
                          //     }
                          //   });
                          // },
                          child: Container(
                              padding: EdgeInsets.symmetric(vertical: 10),
                              child: Text(
                                "$source",
                                style: TextStyle(fontWeight: FontWeight.w500),
                                textAlign: TextAlign.center,
                              )),
                        ),
                      ),
                    ),
                    Image.asset(
                      "images/exchange.png",
                      width: 15,
                      height: 15,
                    ),
                    Expanded(
                      child: Container(
                        // width: double.infinity,
                        margin: EdgeInsets.symmetric(horizontal: 16),
                        child: InkWell(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (_) =>
                                        LanguagePage(target, 1))).then((value) {
                              if (value != null) {
                                target = value;
                                setState(() {});
                              }
                            });
                          },
                          child: Container(
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Color(0xff4474fb)),
                              padding: EdgeInsets.symmetric(vertical: 10),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      "$target",
                                      style: TextStyle(
                                          fontWeight: FontWeight.w500,
                                          color: Colors.white),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                  Icon(
                                    Icons.navigate_next_rounded,
                                    color: Colors.white,
                                  )
                                ],
                              )),
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10)),
                  child: TextField(
                    scrollPhysics: BouncingScrollPhysics(),
                    maxLines: 4,
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                    controller: controller1,
                    focusNode: focusNode1,
                    decoration: InputDecoration(
                      hintText: "Input your words here",
                      border: InputBorder.none,
                      contentPadding:
                          EdgeInsets.symmetric(horizontal: 8, vertical: 10),
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                GestureDetector(
                  onTap: trans,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      gradient: LinearGradient(
                          colors: [Color(0xff4474fb), Color(0xffaaffaa)]),
                    ),
                    child: Text(
                      "Translate",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                result == null
                    ? Container()
                    : Container(
                        width: double.infinity,
                        // height: MediaQuery.of(context).size.height*0.5,
                        // constraints: BoxConstraints(minHeight: 100,maxHeight: 300),
                        margin:
                            EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                        padding:
                            EdgeInsets.symmetric(horizontal: 8, vertical: 10),
                        decoration: BoxDecoration(
                            color: Color(0xff4477bb),
                            borderRadius: BorderRadius.circular(10)),
                        child: Column(
                          children: [
                            Container(
                              width: double.infinity,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  IconButton(
                                      icon: Icon(
                                        Icons.copy_rounded,
                                        color: Colors.white,
                                      ),
                                      onPressed: copyWords),
                                  IconButton(
                                      icon: Icon(
                                        Icons.ios_share,
                                        color: Colors.white,
                                      ),
                                      onPressed: shareWords),
                                  // IconButton(
                                  //     icon: Icon(
                                  //       Icons.record_voice_over_rounded,
                                  //       color: Colors.white,
                                  //     ),
                                  //     onPressed: playWords),
                                ],
                              ),
                            ),
                            Container(
                                width: double.infinity,
                                child: Text(
                                  "$result",
                                  style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w500),
                                )),
                          ],
                        )),
                histories.isEmpty
                    ? Container()
                    : Container(
                        // width: double.infinity,
                        // margin: EdgeInsets.symmetric(horizontal: 16),
                        child: Column(
                          children: [
                            Container(
                                width: double.infinity,
                                margin: EdgeInsets.symmetric(
                                    horizontal: 16, vertical: 10),
                                child: Text(
                                  "Histories",
                                  style: TextStyle(
                                      fontWeight: FontWeight.w500,
                                      fontSize: 18),
                                  textAlign: TextAlign.start,
                                )),
                            Column(
                              children: histories
                                  .map((e) => ListTile(
                                onTap: (){
                                  Clipboard.setData(ClipboardData(text: e['target']));
                                  Fluttertoast.showToast(msg: "Copy Success!");
                                },
                                trailing: IconButton(
                                  highlightColor: Colors.transparent,
                                  icon: Icon(Icons.close_rounded),
                                  onPressed: (){
                                    histories.remove(e);
                                    setState(() {

                                    });
                                  },
                                ),
                                        title: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              e['source'],
                                              style: TextStyle(
                                                  fontWeight: FontWeight.w500,
                                                  fontSize: 16),
                                            ),

                                            Text(e['target']),
                                          ],
                                        ),
                                      ))
                                  .toList(),
                            )
                          ],
                        ),
                      )
              ],
            )), // es auto-formatting nicer for build methods.
      ),
    );
  }
}
